<template>
  <div class="project-alerts">
    <div class="alerts-header">
      <h1 class="page-title">项目告警</h1>
      <div class="severity-filters">
        <button class="filter-btn" :class="{ active: currentSeverity === 'WARNING' }" @click="setSeverity('WARNING')">
          ⚠️ 警告
        </button>
        <button class="filter-btn" :class="{ active: currentSeverity === 'URGENT' }" @click="setSeverity('URGENT')">
          🚨 紧急
        </button>
      </div>
    </div>

    <div class="alerts-content">
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>加载告警数据中...</p>
      </div>

      <div v-else-if="error" class="error-state">
        <div class="error-icon">❌</div>
        <p>{{ error }}</p>
        <button class="retry-btn" @click="loadAlerts">重试</button>
      </div>

      <div v-else-if="alerts.length === 0" class="empty-state">
        <div class="empty-icon">📋</div>
        <p>暂无{{ currentSeverity === 'WARNING' ? '警告' : '紧急' }}告警</p>
      </div>

      <div v-else class="alerts-list">
        <div v-for="alert in alerts" :key="alert.id" class="alert-card"
          :class="{ 'urgent': alert.severity === 'URGENT' }">
          <div class="alert-header">
            <div class="alert-severity">
              <span class="severity-icon">
                {{ alert.severity === 'URGENT' ? '🚨' : '⚠️' }}
              </span>
              <span class="severity-text">
                {{ alert.severity === 'URGENT' ? '紧急' : '警告' }}
              </span>
            </div>
            <div class="alert-date">{{ formatDate(alert.alert_date) }}</div>
          </div>

          <div class="alert-body">
            <h3 class="project-code">{{ alert.project_code }}</h3>
            <p class="customer-name">{{ alert.customer_name }}</p>

            <div class="alert-metrics">
              <div class="metric">
                <span class="metric-label">项目结束日期:</span>
                <span class="metric-value">{{ formatDate(alert.project_end_date) }}</span>
              </div>
              <div class="metric">
                <span class="metric-label">距离80%进度:</span>
                <span class="metric-value">{{ alert.days_to_80_percent }}天</span>
              </div>
              <div class="metric">
                <span class="metric-label">合同总天数:</span>
                <span class="metric-value">{{ alert.total_contract_days }}天</span>
              </div>
            </div>

            <div class="alert-details">
              <h4>告警详情</h4>
              <div v-for="(detail, detailType) in alert.alert_details" :key="detailType" class="detail-item">
                <span class="detail-label">{{ detailType }}:</span>
                <div class="detail-content">
                  <span class="supplement">需补充: {{ detail.need_supplement }}</span>
                  <span class="completion">完成比例: {{ detail.completion_ratio }}</span>
                </div>
              </div>
            </div>

            <div class="alert-footer">
              <span class="alert-count">告警数量: {{ alert.total_alert_count }}</span>
              <span class="update-time">更新时间: {{ formatDateTime(alert.updated_time) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页控件 -->
      <div v-if="alerts.length > 0" class="pagination">
        <button class="page-btn" :disabled="currentPage <= 1" @click="changePage(currentPage - 1)">
          上一页
        </button>
        <span class="page-info">
          第 {{ currentPage }} 页 / 共 {{ totalPages }} 页 (总计 {{ totalItems }} 条)
        </span>
        <button class="page-btn" :disabled="currentPage >= totalPages" @click="changePage(currentPage + 1)">
          下一页
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { alertsService, type ProjectAlert, type AlertSeverity } from '../api/services/alerts'

// 响应式数据
const alerts = ref<ProjectAlert[]>([])
const loading = ref(false)
const error = ref<string | null>(null)
const currentSeverity = ref<AlertSeverity>('WARNING')
const currentPage = ref(1)
const pageSize = ref(10)
const totalPages = ref(0)
const totalItems = ref(0)

// 设置告警严重程度
const setSeverity = (severity: AlertSeverity) => {
  currentSeverity.value = severity
  currentPage.value = 1
  loadAlerts()
}

// 切换页面
const changePage = (page: number) => {
  currentPage.value = page
  loadAlerts()
}

// 加载告警数据
const loadAlerts = async () => {
  try {
    loading.value = true
    error.value = null

    const response = await alertsService.getProjectAlerts({
      severity: currentSeverity.value,
      page: currentPage.value,
      page_size: pageSize.value
    })

    if (response.code === 200) {
      alerts.value = response.data.items || []
      totalPages.value = response.data.total_pages || 0
      totalItems.value = response.data.total || 0
      currentPage.value = response.data.page || 1
    } else {
      throw new Error(response.message || '获取告警数据失败')
    }
  } catch (err) {
    console.error('加载告警数据失败:', err)
    error.value = err instanceof Error ? err.message : '加载告警数据失败'
    alerts.value = []
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN')
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN')
}

// 组件挂载时加载数据
onMounted(() => {
  loadAlerts()
})
</script>

<style scoped>
.project-alerts {
  padding: 30px;
  max-width: 1400px;
  margin: 0 auto;
}

.alerts-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #2d3748;
  margin: 0;
}

.severity-filters {
  display: flex;
  gap: 12px;
}

.filter-btn {
  padding: 10px 20px;
  border: 2px solid #e2e8f0;
  background: white;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #64748b;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-btn:hover {
  border-color: #cbd5e0;
  background: #f8fafc;
}

.filter-btn.active {
  border-color: #3182ce;
  background: #3182ce;
  color: white;
}

.alerts-content {
  min-height: 400px;
}

.loading-state,
.error-state,
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e2e8f0;
  border-top: 4px solid #3182ce;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.error-icon,
.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.retry-btn {
  margin-top: 16px;
  padding: 10px 20px;
  background: #3182ce;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s ease;
}

.retry-btn:hover {
  background: #2c5aa0;
}

.alerts-list {
  display: grid;
  gap: 20px;
}

.alert-card {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.alert-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.alert-card.urgent {
  border-left: 4px solid #e53e3e;
}

.alert-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.alert-severity {
  display: flex;
  align-items: center;
  gap: 8px;
}

.severity-icon {
  font-size: 20px;
}

.severity-text {
  font-weight: 600;
  color: #2d3748;
}

.alert-date {
  color: #64748b;
  font-size: 14px;
}

.alert-body h3 {
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
  margin: 0 0 8px 0;
}

.customer-name {
  color: #64748b;
  margin: 0 0 20px 0;
}

.alert-metrics {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.metric {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.metric-label {
  font-size: 12px;
  color: #64748b;
  font-weight: 500;
}

.metric-value {
  font-size: 16px;
  font-weight: 600;
  color: #2d3748;
}

.alert-details {
  background: #f8fafc;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.alert-details h4 {
  font-size: 14px;
  font-weight: 600;
  color: #2d3748;
  margin: 0 0 12px 0;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-label {
  font-size: 12px;
  color: #64748b;
  font-weight: 500;
}

.detail-content {
  display: flex;
  gap: 16px;
}

.supplement,
.completion {
  font-size: 14px;
  font-weight: 500;
}

.supplement {
  color: #e53e3e;
}

.completion {
  color: #2d3748;
}

.alert-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #64748b;
  border-top: 1px solid #e2e8f0;
  padding-top: 16px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 30px;
  padding: 20px;
}

.page-btn {
  padding: 8px 16px;
  border: 1px solid #e2e8f0;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s ease;
}

.page-btn:hover:not(:disabled) {
  border-color: #3182ce;
  color: #3182ce;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: #64748b;
}

@media (max-width: 768px) {
  .project-alerts {
    padding: 20px;
  }

  .alerts-header {
    flex-direction: column;
    gap: 20px;
    align-items: flex-start;
  }

  .page-title {
    font-size: 24px;
  }

  .alert-metrics {
    grid-template-columns: 1fr;
  }

  .detail-content {
    flex-direction: column;
    gap: 8px;
  }

  .alert-footer {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
}
</style>